//
//  LoginViewController.m
//  CreditHub
//
//  Created by chenglang on 2024/9/12.
//

#import "LoginViewController.h"
#import "LoginService.h"
#import "CacheTool.h"
#import "WebViewController.h"

@interface LoginViewController ()<UITextFieldDelegate>
@property (nonatomic) NSInteger countdownTime;
@property (nonatomic, strong) NSTimer *timer;
@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.pointType = @"1";
//    self.textPhone.text = @"1234567891";
//    self.textCode.text =@"241234";
    
//    [self.textPhone addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
//    [self.textCode addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    self.btnLogin.userInteractionEnabled = YES;
    self.btnLogin.backgroundColor = AppThemeColor;
    [self.btnLogin setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
}

- (void)textFieldDidChange:(UITextField *)textField {
    
    if( self.textCode.text.length > 0 && self.textPhone.text.length > 0 ){
        self.btnLogin.backgroundColor = AppThemeColor;
        self.btnLogin.userInteractionEnabled = YES;
        [self.btnLogin setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
    }else{
        self.btnLogin.backgroundColor = BgGrayColor;
        self.btnLogin.userInteractionEnabled = NO;
        [self.btnLogin setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    }
}

- (IBAction)clickCode:(id)sender {
    
//    if(self.textPhone.text.length == 0){
//        xhl_showMessage(@"Please enter your phone number");
//        return;
//    }
    
    [self requestSendCode];
    
}
- (IBAction)clickVoiceCode:(id)sender {
    
    [self requestSendVoiceCode];
}
- (IBAction)clickLogin:(id)sender {
//    if(self.textPhone.text.length == 0){
//        xhl_showMessage(@"Please enter your phone number");
//        return;
//    }
//    if(self.textCode.text.length == 0){
//        xhl_showMessage(@"Silakan masukkan kode verifikasi");
//        return;
//    }
    if(!self.btnAgreed.selected){
        xhl_showMessage(@"Please read and agree to the Privacy Agreement");
        return;
    }
    [self requestLogin];
}
- (IBAction)clickAgreed:(id)sender {
    self.btnAgreed.selected = !self.btnAgreed.selected;
}
- (IBAction)clickPrivacy:(id)sender {
    
    WebViewController *web = [[WebViewController alloc] init];
    web.url = @"https://macrofil-investments.com/CreditPrivacyPolicy.html";
    [self.navigationController pushViewController:web animated:YES];

}
- (void)startCountdown {
    self.countdownTime = 60;
    [self updateButtonTitle];
    __weak typeof(self) weakSelf = self;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
        weakSelf.countdownTime--;
        [weakSelf updateButtonTitle];
        if (weakSelf.countdownTime <= 0) {
            [timer invalidate];
            weakSelf.timer = nil;
        }
    }];
}
- (void)updateButtonTitle {
    if (self.countdownTime > 0) {
        [self.btnCode setTitle:[NSString stringWithFormat:@"%lds", (long)self.countdownTime] forState:UIControlStateNormal];
        self.btnCode.userInteractionEnabled = NO;
        self.btnCode.backgroundColor = colorWithHex(0xE2DEB3);
        [self.btnCode setTitleColor:colorWithHex(0x151940) forState:UIControlStateNormal];
    } else {
        [self.btnCode setTitle:@"Code" forState:UIControlStateNormal];
        self.btnCode.userInteractionEnabled = YES;
        self.btnCode.backgroundColor = AppThemeColor;
        [self.btnCode setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
    }
}
- (void)requestSendCode{
    if(CHStringIsEmpty(self.startTime)){
        
        self.startTime = [BaseService getTimeStringSince1970];
    }
    xhl_hudLoading();
    __weak typeof(self) weakSelf = self;
    [LoginService requestSendCode:@{@"withme":self.textPhone.text} success:^(NSURLSessionDataTask *task, id response) {
        
        NSInteger ofexcitement =[[response objectForKey:@"ofexcitement"] integerValue];
        if(ofexcitement == 0){
            xhl_hudDismiss();
            [weakSelf startCountdown];
        }
        xhl_showMessage(CHString(response[@"shared"]));
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        xhl_hudDismiss();
    }];
    
}
- (void)requestSendVoiceCode{
    
    if(CHStringIsEmpty(self.startTime)){
        
        self.startTime = [BaseService getTimeStringSince1970];
    }
    xhl_hudLoading();
    __weak typeof(self) weakSelf = self;
    [LoginService requestSendVoiceCode:@{@"withme":self.textPhone.text} success:^(NSURLSessionDataTask *task, id response) {
        
        NSInteger ofexcitement =[[response objectForKey:@"ofexcitement"] integerValue];
        if(ofexcitement == 0){
            xhl_hudDismiss();
            [weakSelf startCountdown];
        }
        xhl_showMessage(CHString(response[@"shared"]));
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        xhl_hudDismiss();
    }];
    
}
- (void)requestLogin{
    
    xhl_hudLoading();
    __weak typeof(self) weakSelf = self;
    [LoginService requestLogin:@{@"cuddle":self.textPhone.text,@"bed":self.textCode.text} success:^(NSURLSessionDataTask *task, id response) {
        
        xhl_hudDismiss();
        xhl_showMessage(CHString(response[@"shared"]));
        NSInteger ofexcitement =[[response objectForKey:@"ofexcitement"] integerValue];
        if(ofexcitement == 0){
           
            [[CacheTool sharedInstance] updateUsetInfo:response[@"pity"]];
            [weakSelf.navigationController popViewControllerAnimated:YES];
            weakSelf.endTime = [BaseService getTimeStringSince1970];
            [weakSelf requestUploadPointType];
        }else{
            weakSelf.textCode.text = @"";
            [weakSelf shakeTextField];
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        xhl_hudDismiss();
        weakSelf.textCode.text = @"";
        [weakSelf shakeTextField];
    }];
    
}
- (void)shakeTextField {
    CABasicAnimation *shake = [CABasicAnimation animationWithKeyPath:@"transform.translation.x"];
    shake.duration = 0.1;
    shake.repeatCount = 5;
    shake.autoreverses = YES;
    shake.fromValue = @(-5);
    shake.toValue = @(5);
    [self.textCode.layer addAnimation:shake forKey:@"shake"];
}
- (void)dealloc {
    [self.timer invalidate];
    self.timer = nil;
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
